#!/bin/bash -e

# output of samtools merge has been sorted.

function info() {
echo Usage: `basename $0` [-t] 'bams.list|in1.bam in2.bam ...'
exit 65
}

while getopts  ":t:p:" opts
do
        case  $opts  in
        t) threads=$OPTARG;;
		p) out_prefix=$OPTARG;;
		\?) info;;
        esac
done
shift $(($OPTIND - 1))


if [ $# -lt 1 ]; then info; fi


. /mnt/ilustre/app/medical/tools/.var

for bam; do
bams="$bams I=$bam";
done 


# echo;echo;echo picard MergeSamFiles
# java $j_mem -jar ${tools_path}/picard-tools-1.119/MergeSamFiles.jar \
# $bams \
# O=$out_prefix.merge.bam \
# CREATE_INDEX=true

if test $# -gt 1; then
samtools merge -f -@$threads $out_prefix.merge.bam $@ && samtools index $out_prefix.merge.bam
else 
samtools merge -f -@$threads -b $1 $out_prefix.merge.bam && samtools index $out_prefix.merge.bam
fi

. $cmd_done